<script setup>
import {computed, onMounted, ref, watch} from "vue";
import Login from "@/views/UserIdentity/Login.vue";
import Register from "@/views/UserIdentity/Register.vue";
import ExternalRegister from "@/views/UserIdentity/ExternalRegister.vue";
import {useArticleStore, useUserStore, useBoardStore} from "@/stores/index.js";
import avatar from "@/components/Avatar.vue"
import router from "@/router/index.js";
import {ElMessage} from "element-plus";
import {useRoute} from "vue-router";

const route = useRoute()
const userStore = useUserStore()
const articleStore = useArticleStore()
const boardStore = useBoardStore()

const showHeader = ref(true);

const searchWord = ref("");
const searchType = ref("title"); // 搜索类型：title(标题) 或 username(用户名)

// 获取用户信息
const userInfo = computed(() => userStore.userInfo)
const isLoggedIn = computed(() => userStore.isLoggedIn)
const unreadCount = computed(() => userStore.unreadCount)

const boardList = computed(() => articleStore.boards)

// 使用全局状态管理的板块选择状态
const activePboardId = computed(() => boardStore.activePboardId)
const activeBoardId = computed(() => boardStore.activeBoardId)

const fetchUnreadMessageCount = async () => {
  try {
    await userStore.fetchUnreadMessageCount()
  } catch (error) {
    console.log(error)
  }
}

const boardClickHandler = (board) => {
  // 更新全局板块状态
  boardStore.setActiveBoard(board.pBoardId, null)
  router.push(`/board/${board.pBoardId}`);
}

const subBoardClickHandler = (board, subBoard) => {
  // 更新全局板块状态
  boardStore.setActiveBoard(board.pBoardId, subBoard.boardId)
  router.push(`/board/${board.pBoardId}/${subBoard.boardId}`);
}

//获取滚动条的高度
const getScrollTop = () => {
  let scrollTop =
      document.documentElement.scrollTop ||
      window.pageYOffset ||
      document.body.scrollTop;
  return scrollTop;
};

const initScroll = () => {
  let initScrollTop = getScrollTop();
  let scrollType = 0;
  let ticking = false;

  const handleScroll = () => {
    let currentScrollTop = getScrollTop();

    if (currentScrollTop > initScrollTop) {
      //往下滚动
      scrollType = 1;
    } else {
      //往上滚动
      scrollType = 0;
    }

    initScrollTop = currentScrollTop;

    // 优化的显示隐藏逻辑
    if (scrollType === 1 && currentScrollTop > 100) {
      showHeader.value = false;
    } else if (scrollType === 0 || currentScrollTop <= 50) {
      showHeader.value = true;
    }

    ticking = false;
  };

  window.addEventListener("scroll", () => {
    if (!ticking) {
      requestAnimationFrame(handleScroll);
      ticking = true;
    }
  });
};

const doSearch = () => {
  if (!searchWord.value.trim()) {
    ElMessage.warning('Please input keyword');
    return;
  }
  
  // 跳转到搜索结果页面，通过路由参数传递搜索信息
  router.push({
    path: '/search',
    query: {
      keyword: searchWord.value.trim(),
      type: searchType.value
    }
  });
}

// Login组件引用
const loginRef = ref()
const registerRef = ref()
const externalRegisterRef = ref()

// 登录
const doLogin = () => {
  loginRef.value.openLoginDialog()
}

// 注册
const doRegister = () => {
  registerRef.value.openRegisterDialog()
}

// 外部用户注册
const doExternalRegister = () => {
  externalRegisterRef.value.openExternalRegisterDialog()
}

// 退出登录
const doLogout = async () => {
  try {
    await userStore.logout()
  } catch (error) {
    ElMessage.error('Logout Failed:', error);
  } finally {
    router.push('/');
  }
}

// 去用户中心
const goToUcenter = (userId) => {
  router.push(`/user/${userId}`);
}


onMounted(() => {
  initScroll();
  articleStore.fetchBoards()
  // 初始化时根据当前路由更新板块状态
  boardStore.updateBoardFromRoute(route)
})

// 监听路由变化，自动同步板块状态
watch(route, (newRoute) => {
  boardStore.updateBoardFromRoute(newRoute)
  // 如果登录，获取未读信息数量
  if(isLoggedIn.value) {
    fetchUnreadMessageCount()
  }
}, { immediate: true })
</script>

<template>
  <div>
    <!--    头部-->
    <div class="header" :class="{ 'header-hidden': !showHeader }">
      <div class="header-content">
        <!--logo-->
        <router-link to="/" class="logo">
          <img src="@/assets/logo.png" alt="logo">
        </router-link>
        <!--        板块分类-->
        <div class="menu-panel">
          <!--          板块列表下拉框-->
          <template v-for="item in boardList">
            <el-dropdown v-if="item.children.length > 0" placement="bottom-start" class="menu-item" :teleported="false">
            <span
                :class="[
                    'menu-item',
                    item.pBoardId == activePboardId ? 'active' : '',
                  ]"
                @click="boardClickHandler(item)"
            >
              {{ item.boardName }}
            </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item v-for="subBoard in item.children">
                    <div class="sub-board-list">
                      <span
                          :class="['sub-board', subBoard.boardId == activeBoardId ? 'active' : '']"
                          @click="subBoardClickHandler(item, subBoard)"
                      >
                        {{ subBoard.boardName }}
                      </span>
                    </div>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
            <span
                v-else
                :class="[
                    'menu-item home',
                    item.pBoardId == activePboardId ? 'active' : '',
                  ]"
                @click="boardClickHandler(item)"
            >
              {{ item.boardName }}
            </span>
          </template>

        </div>
        <div class="user-info-panel">
          <!--          搜索框-->
          <div class="search-box">
            <div class="search-input-container">
              <el-input
                  v-model="searchWord"
                  :placeholder="searchType === 'title' ? 'Please input keywords' : 'Please input username'"
                  clearable
                  class="search-input"
                  size="large"
              >
                <template #prepend>
                  <el-select
                      v-model="searchType"
                      class="search-type-selector"
                      size="large"
                  >
                    <el-option
                        label="Title"
                        value="title"
                    />
                    <el-option
                        label="User"
                        value="username"
                    />
                  </el-select>
                </template>
              </el-input>
            </div>
            <el-button class="header-button" type="primary" size="large" @click="doSearch">Search</el-button>
          </div>
          <!--          用户容器-->
          <div v-if="isLoggedIn" class="user-message-container">
            <!--            消息信息-->
            <div class="message-info">
              <el-dropdown>
                <el-badge :value="unreadCount.totalUnread" :hidden="unreadCount.totalUnread == 0" class="item">
                  <el-icon :size="24">
                    <BellFilled/>
                  </el-icon>
                </el-badge>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item>
                      <router-link to="/user/message/reply">
                        Reply me
                        <span class="tag" v-if="unreadCount.replyUnread > 0">{{unreadCount.replyUnread}}</span>
                      </router-link>
                    </el-dropdown-item>
                    <el-dropdown-item>
                      <router-link to="/user/message/like">
                        Like me
                        <span class="tag" v-if="unreadCount.likeUnread > 0">{{unreadCount.likeUnread}}</span>
                      </router-link>
                    </el-dropdown-item>
                    <el-dropdown-item>
                      <router-link to="/user/message/system">
                        System info
                        <span class="tag" v-if="unreadCount.sysUnread > 0">{{unreadCount.sysUnread}}</span>
                      </router-link>
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
            <!--            用户信息-->
            <div class="user-info">
              <el-dropdown>
                <div class="user-info-box">
                  <avatar
                      :src="userInfo.avatar"
                      :width="50"
                      :addLink="false"
                  ></avatar>
                  <span class="user-name">{{ userInfo.nickName }}</span>
                </div>

                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item @click="goToUcenter(userInfo.userId)">My Homepage</el-dropdown-item>
                    <el-dropdown-item v-if="userInfo.isSuperuser">
                      <a href="http://anki6688.ddns.net:8000/admin/" target="_blank">
                        Admin System
                      </a>
                    </el-dropdown-item>
                    <el-dropdown-item @click="doLogout">Logout</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </div>

          <!--          登录和注册按钮-->
          <div class="login-button" v-else>
            <el-button class="header-button" size="large" type="primary" plain @click="doLogin"
            >Login
            </el-button>
            <el-button class="header-button" size="large" type="primary" plain @click="doRegister"
            >Register
            </el-button>
          </div>
        </div>
      </div>
    </div>
    <!--    主体-->
    <div class="body-content">
      <router-view/>
    </div>
    <!--    底部-->
    <div class="footer">
      <div
          class="footer-content"
      >
        <el-row>
          <el-col :span="6" class="item">
            <div class="logo">
              <div class="logo-letter">
                <span>Campus Nexus</span>
              </div>
              <div class="info">New Generation Campus Forum</div>
            </div>
          </el-col>
          <el-col :span="6" class="item">
            <div class="title">Website Related</div>
            <div><a href="https://www.uic.edu.cn/">BNBU</a></div>
            <div><a href="https://www.hkbu.edu.hk/">HKBU</a></div>
            <div><a href="https://www.bnu.edu.cn/">BNU</a></div>
          </el-col>
          <el-col :span="6" class="item">
            <div class="title">Friendship Links</div>
            <div><a href="https://www.aliyun.com/">Aliyun</a></div>
            <div><a href="https://vuejs.org/">VUE</a></div>
            <div><a href="http://www.djangoproject.com/">Django</a></div>
          </el-col>
          <el-col :span="6" class="item">
            <div class="title">Contact Us</div>
            <div><span>Tel: 0756-3620000</span></div>
            <div><span>Email: uicar@uic.edu.cn</span></div>
          </el-col>
        </el-row>
      </div>
    </div>
  </div>

  <Login ref="loginRef" @openRegister="doRegister"></Login>
    <Register ref="registerRef" @openLogin="doLogin" @openExternalRegister="doExternalRegister"></Register>
    <ExternalRegister ref="externalRegisterRef" @openLogin="doLogin" @openRegister="doRegister"></ExternalRegister>
</template>

<style scoped lang="scss">
.header {
  top: 0px;
  width: 100%;
  position: fixed;
  box-shadow: 0 2px 6px 0 #ddd;
  z-index: 1000;
  background: #fff;
  transform: translateY(0);
  transition: transform 0.3s ease-in-out;

  &.header-hidden {
    transform: translateY(-100%);
  }

  .header-content {
    width: 1300px;
    margin: 0px auto;
    align-items: center;
    height: 60px;
    display: flex;

    .logo {
      display: block;
      margin-right: 5px;

      img {
        height: 60px;
      }
    }

    .menu-panel {
      flex: 1;
      display: flex;
      align-items: center;

      .menu-item {
        display: flex;
        align-items: center;
        margin-left: 8px;
        cursor: pointer;
        font-size: 18px;
        border: none;
        outline: none;
      }

      .home {
        text-decoration: none;
        color: #000;
        line-height: 18px;
        margin-left: 15px;
      }

      .active {
        color: var(--el-color-primary);
      }
    }

    .user-info-panel {
      display: flex;
      align-items: center;

      .search-box {
        display: flex;
        align-items: center;
        gap: 5px;
        width: 100%;

        .search-input-container {
          flex: 1;

          .search-input {
            font-size: 18px;
            width: 320px;

            .el-input-group__prepend {
              padding: 0;
              background: transparent;
              border: none;

              .search-type-selector {
                width: 100px;
                border: none;

                .el-input__wrapper {
                  border: none;
                  box-shadow: none;
                  background: transparent;
                }

                .el-input__inner {
                  text-align: center;
                  font-size: 14px;
                  color: #606266;
                }
              }
            }
          }
        }

        .header-button {
          border-radius: 5px;
          margin-left: 0;
        }
      }

      .user-message-container {
        display: flex;
        align-items: center;
        gap: 15px;
        margin-left: 20px;

        .message-info {
          display: flex;
          align-items: center;
          margin-right: 10px;


        }

        .user-info {
          .user-info-box {
            display: flex;
            align-items: center;
            gap: 8px;

            .user-name {
              font-size: 18px;
              font-weight: 500;
            }
          }
        }
      }

      .login-button {
        margin-left: 10px;
        display: flex;
        align-items: center;
      }
    }
  }
}

.header-button {
  font-size: 18px;
}

.body-content {
  margin-top: 60px;
  position: relative;
  min-height: calc(100vh - 210px);
}

.footer {
  background: #e9e9e9;
  height: 140px;
  margin-top: 10px;

  .footer-content {
    width: 1200px;
    margin: 0px auto;
    padding-top: 10px;

    .item {
      text-align: left;

      .title {
        font-size: 18px;
        margin-bottom: 10px;
      }

      a {
        font-size: 14px;
        text-decoration: none;
        color: var(--text2);
        line-height: 25px;
      }
    }

    .logo {
      .logo-letter {
        font-size: 30px;

        span {
          color: #1A3E6E;
        }
      }

      .info {
        margin-top: 10px;
        color: rgb(93, 91, 91);
      }
    }
  }
}

.tag {
  color: #ffffff;
  background-color: var(--el-color-danger);
}

</style>